package com.jinhua.huaoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinhua.huaoj.common.ErrorCode;
import com.jinhua.huaoj.constant.CommonConstant;
import com.jinhua.huaoj.exception.BusinessException;
import com.jinhua.huaoj.exception.ThrowUtils;
import com.jinhua.huaoj.mapper.QuestionSubmitMapper;
import com.jinhua.huaoj.model.dto.questionSubmit.QuestionSubmitAddRequest;
import com.jinhua.huaoj.model.dto.questionSubmit.QuestionSubmitQueryRequest;
import com.jinhua.huaoj.model.entity.Question;
import com.jinhua.huaoj.model.entity.QuestionSubmit;
import com.jinhua.huaoj.model.entity.User;
import com.jinhua.huaoj.model.enums.QuestionSubmitLanguageEnum;
import com.jinhua.huaoj.model.enums.QuestionSubmitStateEnum;
import com.jinhua.huaoj.model.enums.UserRoleEnum;
import com.jinhua.huaoj.model.vo.QuestionSubmitVO;
import com.jinhua.huaoj.service.QuestionService;
import com.jinhua.huaoj.service.QuestionSubmitService;
import com.jinhua.huaoj.service.UserService;
import com.jinhua.huaoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 20289
 * @description 针对表【question_submit(题目提交)】的数据库操作Service实现
 * @createDate 2024-09-28 13:44:09
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {


    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;


    /**
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public Long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        Long questionId = questionSubmitAddRequest.getQuestionId();
        String language = questionSubmitAddRequest.getLanguage();
        String code = questionSubmitAddRequest.getCode();


//        检查编程语言是否合法
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        ThrowUtils.throwIf(languageEnum == null, ErrorCode.NOT_FOUND_LANGUAGE_ERROR);
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        QuestionSubmit questionSubmit = new QuestionSubmit();

        questionSubmit.setQuestionId(questionId);
        questionSubmit.setUserId(loginUser.getId());
        questionSubmit.setLanguage(language);
        questionSubmit.setCode(code);
        questionSubmit.setState(QuestionSubmitStateEnum.WAITING.getValue());

        boolean save = this.save(questionSubmit);
        ThrowUtils.throwIf(!save,ErrorCode.SYSTEM_ERROR,"题目提交插入失败");

        return questionSubmit.getId();

    }

    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        Long id = questionSubmitQueryRequest.getId();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String language = questionSubmitQueryRequest.getLanguage();
        Integer state = questionSubmitQueryRequest.getState();


        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();


        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(state), "state", state);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);

        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取VO类
     * @param questionSubmit    传入的题目提交信息
     * @param request 为或许获取用户信息做准备
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, HttpServletRequest request) {
        //检查参数适合合法
        if (questionSubmit == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);

        //通过VO的objToVO方法获取VO类 获取的VO类 title字段没有赋值 需要查询数据库进行赋值
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        //只有本人或者管理员才能查看代码
        if (
                ObjectUtils.notEqual(loginUser.getId(),questionSubmit.getUserId()) &&
                        !UserRoleEnum.ADMIN.getValue().equals(loginUser.getUserRole())
        ){
            questionSubmitVO.setCode(null);
        }
        //为title字段赋值
        Question question = questionService.getById(questionSubmit.getQuestionId());
        questionSubmitVO.setTitle(question.getTitle());

        return questionSubmitVO;
    }


    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, HttpServletRequest request) {


        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(
                questionSubmitPage.getCurrent()
                ,questionSubmitPage.getSize()
                ,questionSubmitPage.getTotal()
        );
        List<QuestionSubmit> records = questionSubmitPage.getRecords();
        if (records.isEmpty()) {
            return questionSubmitVOPage;
        }

        List<QuestionSubmitVO> questionSubmitVOList = records.stream().map(questionSubmit -> {
            //通过getVO方法获取转换 title字段需要查询数据手动填入
            QuestionSubmitVO questionSubmitVO = this.getQuestionSubmitVO(questionSubmit, request);

            Question question = questionService.getById(questionSubmit.getQuestionId());
            questionSubmitVO.setTitle(question.getTitle());

            return questionSubmitVO;
        }).collect(Collectors.toList());

        questionSubmitVOPage.setRecords(questionSubmitVOList);

        return questionSubmitVOPage;
    }


}




